import dynamicRouter from '@/router/modules/index.js'
import { constantRoutes } from '@/router/router.config.js'
import { resetRouter } from '@/router'

// 过滤路由
function filterRoute(role, routers) {
  console.log('--------routers:', routers, '----', role)
  const arr = routers.filter(v => {
    // console.log('---v:--', v)
    if (v.children) {
      v.children = filterRoute(role, v.children)
    }
    if (v.meta && v.meta.roles) {
      return v.meta.roles.includes(role)
    } else {
      return true
    }
  })

  // console.log('----===:', arr)
  return arr
}

// console.log(filterRoute)

const state = {
  routes: []
}
const mutations = {
  getRoute(state, payload) {
    const r = filterRoute(payload, dynamicRouter)
    state.routes = [...constantRoutes, ...r].filter(v => v.path !== '/login')
    resetRouter()
  }
}
const actions = {
  getRoute({ commit, state }, payload) {
    return new Promise(resolve => {
      commit('getRoute', payload)
      resolve(state.routes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
